<template>
  <div class="wrapper">
    <el-form :model="formItem" :rules="rules" ref="formRef" :label-width="80">
      <el-form-item label="头像">
        <!--        <Avatar v-if="formItem.face" :src="formItem.face" size="80"/>-->
        <el-avatar v-if="formItem.avatar" :src="formItem.avatar" size="80"/>
        <!--        <Avatar v-else icon="ios-person" size="80"/>-->
        <el-avatar v-else :icon="Avatar" :size="80"/>
      </el-form-item>
      <el-form-item>
        <el-upload ref='upload' :before-upload='beforeAvatarUpload' :headers='accessToken' :on-success='handleSuccess'
                   :action="action" list-type="picture-card" :auto-upload="true" :limit='1' :on-exceed='handleExceed'>
          <el-icon><Plus /></el-icon>

          <template #file="{ file }">
            <div>
              <img class="el-upload-list__item-thumbnail" :src="imgUrl"  style='height: 100%;' alt="" />
              <span class="el-upload-list__item-actions">
          <span
            class="el-upload-list__item-preview"
            @click="handlePictureCardPreview(file)"
          >
            <el-icon><zoom-in /></el-icon>
          </span>
          <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleRemove(file)"
          >
            <el-icon><Delete /></el-icon>
          </span>
        </span>
            </div>
          </template>
        </el-upload>

        <el-dialog v-model="dialogVisible">
          <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input class="wrapper-user-name" style="width:187px" v-model="formItem.nickname" placeholder="" />
      </el-form-item>
      <el-form-item label="手机" prop="mobile">
        <el-input class="wrapper-user-name" style="width:187px" v-model="formItem.mobile" placeholder="" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="save">修改</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang='ts'>
import storage from '@/utils/storage.ts';
import { getUserInfo, updateUser } from '@/api/sys/user'
import { commonUrl } from '@/utils/request.ts';
import { onMounted, reactive, ref } from 'vue'
import { ElMessage, type UploadInstance, type UploadProps, type UploadRawFile } from 'element-plus'
import { Avatar,Plus,ZoomIn,Delete } from '@element-plus/icons-vue'

const formRef = ref()
const rules = reactive({ // 验证规则
  nickName: [{required: true, message: '请填写昵称'},
    { max: 16, message: '昵称最多允许输入16位'}]
})
const imgUrl = ref('')
const imgPath = ref('')
const formItem = reactive({
  avatar: undefined,
  username: undefined,
  nickname: undefined,
  mobile: undefined,
}) // 表单数据
const action = ref('/dev/api/v1/common/upload') // 上传接口
const token = reactive({
  'Authorization': ''
}) // 验证token
const fileList = reactive([])
function save () { // 保存
  formRef.value.validate(valid => {
    if (valid) {
      let params = {
        id: user.value.id,
        avatar: imgPath.value,
        nickname: formItem.nickname,
        mobile: formItem.mobile,
      }
      updateUser(1,params).then(res => {
        if (res.code === '00000') {
          ElMessage.success('修改成功')
          formItem.avatar = imgUrl.value
          storage.setItem('userInfo', res.result)
        }
      })
    }
  })
}
const user = ref(storage.getItem('userInfo'))
const disabled = ref(false)
const dialogImageUrl = ref()
const dialogVisible = ref()
const baseUrl = import.meta.env.VITE_APP_URL
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('只能上传jpg格式的图片!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 1) {
    ElMessage.error('图片不能大于1MB!')
    return false
  }
  return true
}
const handleSuccess = (res,file)=>{
  if(res.code === '00000'){
    imgUrl.value = res.data
    imgPath.value = res.data
    formItem.avatar = imgUrl.value
  }
}
const handleRemove: UploadProps['onRemove'] = (uploadFile) => {
  console.log(uploadFile)
  uploadFile.url = ''
  imgUrl.value = ''
}
const upload = ref<UploadInstance>()
const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = new Date().valueOf();
  upload.value!.handleStart(file)
}
// function handleSuccess (res, file) { // 上传成功
//   this.$set(this.formItem, 'face', res.result)
// }

onMounted(()=>{
  getUserInfo().then((resp)=>{
    user.value = resp.data
    console.log('onmounted__userInfo',user.value)
    Object.assign(formItem,user.value)
    formItem.avatar = resp.data.avatar
  })

  token.Authorization = storage.getItem('accessToken');
})
</script>

<style scoped>

</style>
